package com.chinasoft.ecommerceconsumptionanalysissystem.controller;


import com.chinasoft.ecommerceconsumptionanalysissystem.controller.Exception.DataNotFoundException;
import com.chinasoft.ecommerceconsumptionanalysissystem.controller.requestbody.*;
import com.chinasoft.ecommerceconsumptionanalysissystem.pojo.*;
import com.chinasoft.ecommerceconsumptionanalysissystem.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/electronics")
@CrossOrigin //支持跨域
public class UserController {
    @Autowired
    private ElectronicsSaleService electronicsSaleService;

    @Autowired
    private AbnormalConsumeUserService abnormalConsumeUserService;

    @Autowired
    private AbnormalHighPriceOrderService abnormalHighPriceOrderService;

    @Autowired
    private BrandShareInCategoryService brandShareInCategoryService;

    @Autowired
    private CategoryByAgeLayerService categoryByAgeLayerService;

    @Autowired
    private CategoryByProvinceService categoryByProvinceService;

    @Autowired
    private CategoryBySexService categoryBySexService;

    @Autowired
    private CategoryRatioService categoryRatioService;

    @Autowired
    private CtByDayService ctByDayService;

    @Autowired
    private CtByLocalAndTimeService ctByLocalAndTimeService;

    @Autowired
    private CtByLocalService ctByLocalService;

    @Autowired
    private CtByMonthService ctByMonthService;

    @Autowired
    private CtByWeekService ctByWeekService;

    @Autowired
    private HighRepurchaseBrandService highRepurchaseBrandService;

    @Autowired
    private HighRepurchaseCategoryService highRepurchaseCategoryService;

    @Autowired
    private KpiService kpiService;

    @Autowired
    private ProductCombinationService productCombinationService;

    @Autowired
    private ProductRepurchaseRateService productRepurchaseRateService;

    @Autowired
    private RepeatOrderByUserService repeatOrderByUserService;

    @Autowired
    private UserPowerByAgeLayerService userPowerByAgeLayerService;

    @Autowired
    private UserPowerByProvinceService userPowerByProvinceService;

    @Autowired
    private UserPowerBySexService userPowerBySexService;

    @GetMapping("/kpi")
    public ResponseEntity<Object> getKpiData(
            @RequestParam String startDate,
            @RequestParam String endDate) {

        // 验证日期参数是否为空
        if (startDate == null || startDate.isEmpty() || endDate == null
                || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 验证日期格式是否正确 (yyyy-MM-dd)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false); // 严格校验日期格式
        try {
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);

            // 验证开始日期不能晚于结束日期
            if (start.after(end)) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "开始日期不能晚于结束日期");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);
            System.out.println(start);
            System.out.println(end);
            // 调用服务层获取KPI数据
            Map<String, Object> kpiData = electronicsSaleService.getKPI(start, end);
            System.out.println(kpiData);
            BigInteger salesBigInt = (BigInteger) kpiData.get("sales");
            BigDecimal sales = new BigDecimal(salesBigInt);

            Long ordersLong = (Long) kpiData.get("orders");
            Integer orders = ordersLong.intValue();

            Long usersLong = (Long) kpiData.get("users");
            Integer users = usersLong.intValue();


            Kpi kpi = new Kpi(null,start,end,orders,sales,users,null);
            kpiService.insert(kpi);


            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", kpiData);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/kpi1")
    public ResponseEntity<Object> getKpiData1(
            @RequestParam String startDate,
            @RequestParam String endDate) {

        // 验证日期参数是否为空
        if (startDate == null || startDate.isEmpty() || endDate == null
                || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 验证日期格式是否正确 (yyyy-MM-dd)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false); // 严格校验日期格式
        try {
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);

            // 验证开始日期不能晚于结束日期
            if (start.after(end)) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "开始日期不能晚于结束日期");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);
            // 调用服务层获取KPI数据
            Kpi result=null;
            List<Kpi> kpiData = kpiService.selectAll();
            for(Kpi kpi:kpiData){
                if(kpi.getStartDate().equals(start)&&kpi.getEndDate().equals(end)){
                    result=kpi;
                    break;
                }
            }
            if(result==null){
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "没有该时间段的数据");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }

            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/daily")
    public ResponseEntity<Object> getDailySalesData(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        // 验证日期参数是否为空
        if (startDate == null || startDate.isEmpty() ||
                endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 验证日期格式是否正确 (yyyy-MM-dd)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false); // 严格校验日期格式
        try {
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);

            // 验证开始日期不能晚于结束日期
            if (start.after(end)) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "开始日期不能晚于结束日期");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);
            // 调用服务层获取按日统计的销售数据
            List<Map<String, Object>> dailySalesData = electronicsSaleService.getCTByDay(start, end);
            for(Map<String, Object> map:dailySalesData){
                String dateStr = (String) map.get("date"); // 先获取String类型的日期
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); // 根据实际格式调整
                Date date = sdf1.parse(dateStr); // 解析为Date对象
                BigInteger salesBigInt = (BigInteger) map.get("sales");
                BigDecimal sales = new BigDecimal(salesBigInt);

                Long ordersLong = (Long) map.get("orders");
                Integer orders = ordersLong.intValue();

                Long usersLong = (Long) map.get("users");
                Integer users = usersLong.intValue();
                CtByDay ctByDay=new CtByDay(null,date,sales,orders,users,null);
                ctByDayService.insert(ctByDay);
            }



            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", dailySalesData);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/daily1")
    public ResponseEntity<Object> getDailySalesData1(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        // 验证日期参数是否为空
        if (startDate == null || startDate.isEmpty() ||
                endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 验证日期格式是否正确 (yyyy-MM-dd)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false); // 严格校验日期格式
        try {
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);

            // 验证开始日期不能晚于结束日期
            if (start.after(end)) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "开始日期不能晚于结束日期");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);
            // 调用服务层获取按日统计的销售数据
            List<CtByDay> dailySalesData = ctByDayService.selectAll();
            List<CtByDay> result = new ArrayList<>();
            for(CtByDay ctByDay:dailySalesData){
                if(ctByDay.getDate().compareTo(start) >= 0 &&
                        ctByDay.getDate().compareTo(end) <= 0){
                    result.add(ctByDay);
                }
            }

            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/weekly")
    public ResponseEntity<Object> getWeeklySalesData(
            @RequestParam String sortType,
            @RequestParam String targetDate
    ) {
        // 1. 基础参数非空校验
        if (sortType == null || sortType.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "排序类型不能为空（支持year：按年排序，month：按月排序）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        if (targetDate == null || targetDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "目标日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 排序类型合法性校验（仅支持year/month）
        if (!"year".equals(sortType) && !"month".equals(sortType)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "排序类型不合法，仅支持year（按年排序）或month（按月排序）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setLenient(false);
        Date targetDateObj = null;
        try {
            targetDateObj = sdf.parse(targetDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取数据并处理响应
        try {
            // 调用服务层：传入目标日期（确定所在周）和排序类型，获取按周统计的销售数据
            List<Map<String, Object>> weeklySalesData =
                    electronicsSaleService.getCTByWeek(sortType, targetDateObj);
            for(Map<String, Object> map:weeklySalesData){
                String week = (String) map.get("week");
                BigInteger salesBigInt = (BigInteger) map.get("sales");
                BigDecimal sales = new BigDecimal(salesBigInt);

                Long ordersLong = (Long) map.get("orders");
                Integer orders = ordersLong.intValue();

                Long usersLong = (Long) map.get("users");
                Integer users = usersLong.intValue();
                CtByWeek ctByWeek = new CtByWeek(null, sortType, targetDateObj, week, sales, orders, users, null);
                ctByWeekService.insert(ctByWeek);
            }

            // 构建成功响应（与原有接口格式保持一致）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", weeklySalesData); // data为周内每日销售数据列表

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 服务端异常处理（打印日志+统一错误响应）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/weekly1")
    public ResponseEntity<Object> getWeeklySalesData1(
            @RequestParam String sortType,
            @RequestParam String targetDate
    ) {
        // 1. 基础参数非空校验
        if (sortType == null || sortType.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "排序类型不能为空（支持year：按年排序，month：按月排序）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        if (targetDate == null || targetDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "目标日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 排序类型合法性校验（仅支持year/month）
        if (!"year".equals(sortType) && !"month".equals(sortType)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "排序类型不合法，仅支持year（按年排序）或month（按月排序）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 目标日期格式校验（必须为yyyy-MM-dd）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setLenient(false); // 严格校验日期（避免2023-02-30这类非法日期通过）
        Date targetDateObj = null;
        try {
            targetDateObj = sdf.parse(targetDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd格式（如：2023-10-09）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取数据并处理响应
        try {
            // 调用服务层：传入目标日期（确定所在周）和排序类型，获取按周统计的销售数据
            List<CtByWeek> result = new ArrayList<>();
            List<CtByWeek> weeklySalesData =
                    ctByWeekService.selectAll();
            for(CtByWeek ctByWeek:weeklySalesData){
                SimpleDateFormat sdf1 = null;

                if(ctByWeek.getSortType().equals(sortType)){
                    if(sortType.equals("year")){
                        sdf1 = new SimpleDateFormat("yyyy");
                    }else sdf1 = new SimpleDateFormat("yyyy-MM");
                    String dateStr = sdf1.format(ctByWeek.getTargetDate());
                    Date date1 = sdf1.parse(targetDate);
                    if(date1.equals(sdf1.parse(dateStr))){;
                        result.add(ctByWeek);
                    }
                }

            }
            // 构建成功响应（与原有接口格式保持一致）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result); // data为周内每日销售数据列表

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 服务端异常处理（打印日志+统一错误响应）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/monthly")
    public ResponseEntity<Object> getMonthlySalesData(
            @RequestParam String year
    ) {
        // 1. 校验参数是否为空
        if (year == null || year.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "时间参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 校验时间格式（必须为yyyy-MM-dd HH:mm:ss）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false); // 严格校验时间格式
        Date time;
        try {
            time = sdf.parse(year);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "时间格式不正确，请使用yyyy-MM-dd HH:mm:ss格式（如：2020-04-26 08:45:57）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 从时间中提取年份（格式：yyyy）
        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
        String yeardate = yearFormat.format(time);

        // 4. 调用服务层获取该年份的月度销售数据
        try {
            List<Map<String, Object>> monthlySalesData = electronicsSaleService.getCTByMonth(time);
            for(Map<String, Object> map:monthlySalesData){
                String date = (String) map.get("date");
                BigInteger salesBigInt = (BigInteger) map.get("sales");
                BigDecimal sales = new BigDecimal(salesBigInt);

                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
                Date monthdate = sdf1.parse(date);
                String month = sdf1.format(monthdate);

                Long ordersLong = (Long) map.get("orders");
                Integer orders = ordersLong.intValue();

                Long usersLong = (Long) map.get("users");
                Integer users = usersLong.intValue();
                CtByMonth ctByMonth = new CtByMonth(null, Integer.parseInt(yeardate), month,
                        sales, orders, users, null);
                ctByMonthService.insert(ctByMonth);
            }

            // 5. 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", monthlySalesData);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/monthly1")
    public ResponseEntity<Object> getMonthlySalesData1(
            @RequestParam String year
    ) {
        // 1. 校验参数是否为空
        if (year == null || year.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "时间参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 校验时间格式（必须为yyyy-MM-dd HH:mm:ss）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false); // 严格校验时间格式
        Date time;
        try {
            time = sdf.parse(year);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "时间格式不正确，请使用yyyy-MM-dd HH:mm:ss格式（如：2020-04-26 08:45:57）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 从时间中提取年份（格式：yyyy）
        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
        String yeardate = yearFormat.format(time);

        // 4. 调用服务层获取该年份的月度销售数据
        try {
            List<CtByMonth> result = new ArrayList<>();
            List<CtByMonth> monthlySalesData = ctByMonthService.selectAll();
            for(CtByMonth ctByMonth:monthlySalesData){
                if(ctByMonth.getYear().equals(Integer.parseInt(yeardate))){
                    result.add(ctByMonth);
                }
            }

            // 5. 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/local-time")
    public ResponseEntity<Object> getSalesByRegionAndTime(
            @RequestParam String startDate,
            @RequestParam String endDate
    ) {
        // 1. 校验开始日期和结束日期是否为空
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 校验日期格式（必须为yyyy-MM-dd HH:mm:ss，严格模式避免非法日期）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 校验开始日期不能晚于结束日期
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取地区-时间维度销售数据
        try {
            List<Map<String, Object>> regionTimeSalesData =
                    electronicsSaleService.getCTByLocalAndTime(start, end);
            for(Map<String, Object> map:regionTimeSalesData){
                String province=(String) map.get("province");

                BigInteger salesBigInt = (BigInteger) map.get("sales");
                BigDecimal sales = new BigDecimal(salesBigInt);

                Long ordersLong = (Long) map.get("orders");
                Integer orders = ordersLong.intValue();

                Long usersLong = (Long) map.get("users");
                Integer users = usersLong.intValue();

                CtByLocalAndTime ctByLocalAndTime = new CtByLocalAndTime(null, start, end,
                        province, sales, orders, users, null);
                ctByLocalAndTimeService.insert(ctByLocalAndTime);
            }

            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", regionTimeSalesData);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);

        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/local-time1")
    public ResponseEntity<Object> getSalesByRegionAndTime1(
            @RequestParam String startDate,
            @RequestParam String endDate
    ) {
        // 1. 校验开始日期和结束日期是否为空
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 校验日期格式（必须为yyyy-MM-dd，严格模式避免非法日期）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 校验开始日期不能晚于结束日期
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取地区-时间维度销售数据
        try {
            List<CtByLocalAndTime> regionTimeSalesData = ctByLocalAndTimeService.selectAll();
            List<CtByLocalAndTime> result = new ArrayList<>();
            for(CtByLocalAndTime ctByLocalAndTime:regionTimeSalesData){
                if(ctByLocalAndTime.getStartDate().equals(start) &&
                        ctByLocalAndTime.getEndDate().equals(end)){
                    result.add(ctByLocalAndTime);
                }
            }

            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);

        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/local")
    public ResponseEntity<Object> getSalesByRegionSummary() {
        try {
            // 调用服务层获取所有地区销售汇总数据
            // 服务层需返回List<Map>，每个Map包含"region"、"totalSales"、"proportion"
            List<Map<String, Object>> regionSalesSummary = electronicsSaleService.getCTByLocal();
            System.out.println(regionSalesSummary);
            for(Map<String, Object> map:regionSalesSummary){
                String province=(String) map.get("province");

                BigInteger salesBigInt = (BigInteger) map.get("sales");
                BigDecimal sales = new BigDecimal(salesBigInt);

                Long ordersLong = (Long) map.get("orders");
                Integer orders = ordersLong.intValue();

                Long usersLong = (Long) map.get("users");
                Integer users = usersLong.intValue();

                CtByLocal ctByLocal = new CtByLocal(null, province, sales, orders, users, null);
                ctByLocalService.insert(ctByLocal);
            }

            // 构建成功响应（符合通用成功响应格式）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", regionSalesSummary); // 地区汇总数据列表

            return new ResponseEntity<>(successResponse, HttpStatus.OK);

        } catch (Exception e) {
            // 服务端异常处理（沿用项目统一日志打印+错误响应格式）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500); // 服务器内部错误码
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/local1")
    public ResponseEntity<Object> getSalesByRegionSummary1() {
        try {
            List<CtByLocal> regionSalesSummary = ctByLocalService.selectAll();

            // 构建成功响应（符合通用成功响应格式）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", regionSalesSummary); // 地区汇总数据列表

            return new ResponseEntity<>(successResponse, HttpStatus.OK);

        } catch (Exception e) {
            // 服务端异常处理（沿用项目统一日志打印+错误响应格式）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500); // 服务器内部错误码
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/category-ratio")
    public ResponseEntity<Object> getCategoryRatio() {
        try {
            // 调用服务层获取各品类销量与销售额占比数据
            // 服务层需返回按销量降序排列的列表，每个元素包含指定字段
            List<Map<String, Object>> categoryRatioData = electronicsSaleService.getCategoryRatio();
            for(Map<String, Object> map:categoryRatioData){
                String categoryCode = (String) map.get("category_code");

                Object volumeObj = map.get("volume");
                Integer volume = 0; // 默认值
                if (volumeObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long volumeLong = (Long) volumeObj;
                    volume = volumeLong.intValue();
                } else if (volumeObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    volume = (Integer) volumeObj;
                }

                String volumeRatio = (String) map.get("volume_ratio");
                String salesRatio = (String) map.get("sales_ratio");
                BigInteger salesBigInt = (BigInteger) map.get("sales");
                BigDecimal sales = new BigDecimal(salesBigInt);

                CategoryRatio categoryRatio = new CategoryRatio(null, categoryCode, volume
                        , volumeRatio, sales, salesRatio, null);
                categoryRatioService.insert(categoryRatio);
            }

            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", categoryRatioData);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/category-ratio1")
    public ResponseEntity<Object> getCategoryRatio1() {
        try {
            List<CategoryRatio> categoryRatioData = categoryRatioService.selectAll();

            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", categoryRatioData);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/brand-share")
    public ResponseEntity<Object> getTopBrandShare(
            @RequestParam String categoryCode,
            @RequestParam int topN
    ) {
        // 1. 参数非空及合法性校验
        System.out.println(categoryCode);
        System.out.println(topN);
        if (categoryCode == null || categoryCode.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "品类编码不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        if (topN <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "topN必须为正整数");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            // 调用服务层获取指定品类下前N名品牌的市场份额数据
            List<Map<String, Object>> topBrandData =
                    electronicsSaleService.getBrandShareInCategory(categoryCode, topN);

            for(Map<String, Object> map:topBrandData){
                String brand = (String) map.get("brand");

                Object volumeObj = map.get("volume");
                Integer volume = 0; // 默认值
                if (volumeObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long volumeLong = (Long) volumeObj;
                    volume = volumeLong.intValue();
                } else if (volumeObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    volume = (Integer) volumeObj;
                }

                String volumeShare = (String) map.get("volume_share");

                BigInteger salesBigInt = (BigInteger) map.get("sales");
                BigDecimal sales = new BigDecimal(salesBigInt);

                String salesShare = (String) map.get("sales_share");

                BrandShareInCategory brandShareInCategory = new BrandShareInCategory(null,
                        categoryCode, topN, brand, volume,
                        volumeShare, sales, salesShare, null);
                brandShareInCategoryService.insert(brandShareInCategory);
            }

            // 构建成功响应
            System.out.println(topBrandData);
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", topBrandData);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/brand-share1")
    public ResponseEntity<Object> getTopBrandShare1(
            @RequestParam String categoryCode,
            @RequestParam int topN
    ) {
        // 1. 参数非空及合法性校验
        System.out.println(categoryCode);
        System.out.println(topN);
        if (categoryCode == null || categoryCode.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "品类编码不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        if (topN <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "topN必须为正整数");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            List<BrandShareInCategory> result = new ArrayList<>();
            List<BrandShareInCategory> topBrandData = brandShareInCategoryService.selectAll();
            for(BrandShareInCategory brandShareInCategory:topBrandData){
                if(brandShareInCategory.getCategoryCode().equals(categoryCode)&&
                        brandShareInCategory.getTopN()==topN){
                    result.add(brandShareInCategory);
                }
            }

            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @GetMapping("/product/combination")
    public ResponseEntity<Object> getProductCombinationData(
            @RequestParam int number
    ) {
        // 1. 参数非空及合法性校验
        if (number <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "number必须为正整数");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            // 调用服务层获取商品组合数据
            List<Map<String, Object>> combinationData =
                    electronicsSaleService.getProductCombination(number);
            for(Map<String, Object> map:combinationData){
                String combination = (String) map.get("combination");

                Object combinationCountObj = map.get("combination_count");
                Integer combinationCount = 0; // 默认值
                if (combinationCountObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long combinationCountLong = (Long) combinationCountObj;
                    combinationCount = combinationCountLong.intValue();
                } else if (combinationCountObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    combinationCount = (Integer) combinationCountObj;
                }

                BigInteger combinationRatioint = (BigInteger) map.get("combination_ratio");
                String combinationRatio = combinationRatioint.toString();

                ProductCombination productCombination = new ProductCombination(null,
                        combination, combinationCount, combinationRatio, number, null);
                productCombinationService.insert(productCombination);
            }

            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", combinationData);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/product/combination1")
    public ResponseEntity<Object> getProductCombinationData1(
            @RequestParam int number
    ) {
        // 1. 参数非空及合法性校验
        if (number <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "number必须为正整数");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            List<ProductCombination> combinationData = productCombinationService.selectAll();
            List<ProductCombination> result = new ArrayList<>();
            for(ProductCombination productCombination:combinationData){
                if(productCombination.getTopNumber()==number){
                    result.add(productCombination);
                }
            }

            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/product/repurchase-rate")
    public ResponseEntity<Object> getProductRepurchaseRate(
            @RequestParam String productId,
            @RequestParam String startDate,
            @RequestParam String endDate
    ) {
        long productIdLong = Long.parseLong(productId);
        if (productIdLong <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "productId必须为正整数");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 日期格式校验（yyyy-MM-dd）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 校验开始日期不能晚于结束日期
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            // 调用服务层获取商品复购率数据
            Map<String, Object> repurchaseRateData =
                    electronicsSaleService.getProductRepurchaseRate(productIdLong, start, end);

            Object totalUserPurchaseCountObj = repurchaseRateData.get("total_user_purchase_count");
            Integer totalUserPurchaseCount = 0; // 默认值
            if (totalUserPurchaseCountObj instanceof Long) {
                // 先转为Long，再通过intValue()转为Integer
                Long totalUserPurchaseCountLong = (Long) totalUserPurchaseCountObj;
                totalUserPurchaseCount = totalUserPurchaseCountLong.intValue();
            } else if (totalUserPurchaseCountObj instanceof Integer) {
                // 兼容可能的Integer类型
                totalUserPurchaseCount = (Integer) totalUserPurchaseCountObj;
            }

            Object userRepurchaseSumObj = repurchaseRateData.get("user_repurchase_sum");
            Integer userRepurchaseSum = 0; // 默认值
            if (userRepurchaseSumObj instanceof Long) {
                // 先转为Long，再通过intValue()转为Integer
                Long userRepurchaseSumLong = (Long) userRepurchaseSumObj;
                userRepurchaseSum = userRepurchaseSumLong.intValue();
            } else if (userRepurchaseSumObj instanceof Integer) {
                // 兼容可能的Integer类型
                userRepurchaseSum = (Integer) userRepurchaseSumObj;
            }

            BigInteger productRepurchaseRateint =
                    (BigInteger) repurchaseRateData.get("product_repurchase_rate");
            String productRepurchaseRate = productRepurchaseRateint.toString();
            ProductRepurchaseRate productRepurchaseRateData = new ProductRepurchaseRate(null,
                    productIdLong, start, end, totalUserPurchaseCount,
                    userRepurchaseSum, productRepurchaseRate, null);
            productRepurchaseRateService.insert(productRepurchaseRateData);

            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", repurchaseRateData);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/product/repurchase-rate1")
    public ResponseEntity<Object> getProductRepurchaseRate1(
            @RequestParam String productId,
            @RequestParam String startDate,
            @RequestParam String endDate
    ) {
        long productIdLong = Long.parseLong(productId);
        if (productIdLong <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "productId必须为正整数");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 日期格式校验（yyyy-MM-dd）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 校验开始日期不能晚于结束日期
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            List<ProductRepurchaseRate> repurchaseRateData =
                    productRepurchaseRateService.selectAll();
            ProductRepurchaseRate result = null;
            for(ProductRepurchaseRate repurchaseRate : repurchaseRateData){
                if(repurchaseRate.getProductId() == productIdLong &&
                        repurchaseRate.getStartDate().equals(start) &&
                        repurchaseRate.getEndDate().equals(end)){
                    result = repurchaseRate;
                    break;
                }
            }
            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/brand/high-repurchase")
    public ResponseEntity<Object> getHighRepurchaseBrands(
            @RequestParam int number,
            @RequestParam String startDate,
            @RequestParam String endDate
    ) {
        // 校验number：必须为正整数
        if (number <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "number必须为正整数");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 校验日期非空
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 日期格式校验（严格校验yyyy-MM-dd，避免非法日期如2023-02-30）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 校验开始日期不能晚于结束日期
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取数据并处理响应
        try {
            // 调用服务层：按复购率降序获取前N个品牌数据
            List<Map<String, Object>> highRepurchaseBrands =
                    electronicsSaleService.getHighRepurchaseBrand(number, start, end);
            for(Map<String, Object> highbrand : highRepurchaseBrands){
                String brand = (String) highbrand.get("brand");

                Object totalUserPurchaseCountObj = highbrand.get("total_user_purchase_count");
                Integer totalUserPurchaseCount = 0; // 默认值
                if (totalUserPurchaseCountObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long totalUserPurchaseCountLong = (Long) totalUserPurchaseCountObj;
                    totalUserPurchaseCount = totalUserPurchaseCountLong.intValue();
                } else if (totalUserPurchaseCountObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    totalUserPurchaseCount = (Integer) totalUserPurchaseCountObj;
                }

                Object userRepurchaseSumObj = highbrand.get("user_repurchase_sum");
                Integer userRepurchaseSum = 0; // 默认值
                if (userRepurchaseSumObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long userRepurchaseSumLong = (Long) userRepurchaseSumObj;
                    userRepurchaseSum = userRepurchaseSumLong.intValue();
                } else if (userRepurchaseSumObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    userRepurchaseSum = (Integer) userRepurchaseSumObj;
                }

                BigInteger productRepurchaseRateint =
                        (BigInteger) highbrand.get("product_repurchase_rate");
                String productRepurchaseRate = productRepurchaseRateint.toString();

                HighRepurchaseBrand highRepurchaseBrand = new HighRepurchaseBrand(
                        null,
                        brand,
                        start,
                        end,
                        number,
                        totalUserPurchaseCount,
                        userRepurchaseSum,
                        productRepurchaseRate,
                        null
                );
                highRepurchaseBrandService.insert(highRepurchaseBrand);
            }

            // 构建成功响应（与项目现有接口响应格式一致）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", highRepurchaseBrands);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 服务端异常处理：打印日志+统一错误响应
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/brand/high-repurchase1")
    public ResponseEntity<Object> getHighRepurchaseBrands1(
            @RequestParam int number,
            @RequestParam String startDate,
            @RequestParam String endDate
    ) {
        // 校验number：必须为正整数
        if (number <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "number必须为正整数");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 校验日期非空
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 日期格式校验（严格校验yyyy-MM-dd，避免非法日期如2023-02-30）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 校验开始日期不能晚于结束日期
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取数据并处理响应
        try {
            List<HighRepurchaseBrand> result = new ArrayList<>();
            List<HighRepurchaseBrand> highRepurchaseBrands = highRepurchaseBrandService.selectAll();
            for (HighRepurchaseBrand highRepurchaseBrand : highRepurchaseBrands) {
                if(highRepurchaseBrand.getStartDate().equals(start) &&
                highRepurchaseBrand.getEndDate().equals(end) &&
                highRepurchaseBrand.getTopNumber() == number){
                    result.add(highRepurchaseBrand);
                }
            }

            // 构建成功响应（与项目现有接口响应格式一致）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 服务端异常处理：打印日志+统一错误响应
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/category/high-repurchase")
    public ResponseEntity<Object> getHighRepurchaseCategories(
            @RequestParam int number,
            @RequestParam String startDate,
            @RequestParam String endDate
    ) {

        // 校验number：必须为正整数（错误响应匹配"获取数量必须大于0"）
        if (number < 1) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "获取数量必须大于0");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 校验日期非空：开始日期/结束日期不能为空
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 日期逻辑校验：开始日期不能晚于结束日期
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取数据并处理响应（包含业务异常捕获）
        try {
            // 调用服务层：按复购率降序获取前N个商品类别数据
            List<Map<String, Object>> highRepurchaseCategories =
                    electronicsSaleService.getHighRepurchaseCategory(number, start, end);

            // 校验服务层返回数据是否为空（避免无数据时返回空列表，可选逻辑，根据业务需求调整）
            if (highRepurchaseCategories == null || highRepurchaseCategories.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 404);
                errorResponse.put("message", "未查询到该时间范围内的商品类别数据");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
            for(Map<String, Object> category : highRepurchaseCategories){
                String categoryCode = (String) category.get("category_code");

                Object totalUserPurchaseCountObj = category.get("total_user_purchase_count");
                Integer totalUserPurchaseCount = 0; // 默认值
                if (totalUserPurchaseCountObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long totalUserPurchaseCountLong = (Long) totalUserPurchaseCountObj;
                    totalUserPurchaseCount = totalUserPurchaseCountLong.intValue();
                } else if (totalUserPurchaseCountObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    totalUserPurchaseCount = (Integer) totalUserPurchaseCountObj;
                }

                Object userRepurchaseSumObj = category.get("user_repurchase_sum");
                Integer userRepurchaseSum = 0; // 默认值
                if (userRepurchaseSumObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long userRepurchaseSumLong = (Long) userRepurchaseSumObj;
                    userRepurchaseSum = userRepurchaseSumLong.intValue();
                } else if (userRepurchaseSumObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    userRepurchaseSum = (Integer) userRepurchaseSumObj;
                }

                BigInteger productRepurchaseRateint =
                        (BigInteger) category.get("product_repurchase_rate");
                String productRepurchaseRate = productRepurchaseRateint.toString();

                HighRepurchaseCategory highRepurchaseCategory = new HighRepurchaseCategory(
                        null,
                        categoryCode,
                        start,
                        end,
                        number,
                        totalUserPurchaseCount,
                        userRepurchaseSum,
                        productRepurchaseRate,
                        null
                );
                highRepurchaseCategoryService.insert(highRepurchaseCategory);
            }

            // 构建成功响应（与响应示例格式完全一致）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", highRepurchaseCategories);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 通用服务端异常处理（打印日志+统一500错误响应）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/category/high-repurchase1")
    public ResponseEntity<Object> getHighRepurchaseCategories1(
            @RequestParam int number,
            @RequestParam String startDate,
            @RequestParam String endDate
    ) {

        // 校验number：必须为正整数（错误响应匹配"获取数量必须大于0"）
        if (number < 1) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "获取数量必须大于0");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 校验日期非空：开始日期/结束日期不能为空
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 日期逻辑校验：开始日期不能晚于结束日期
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取数据并处理响应（包含业务异常捕获）
        try {
            List<HighRepurchaseCategory> highRepurchaseCategories =
                    highRepurchaseCategoryService.selectAll();
            List<HighRepurchaseCategory> result = new ArrayList<>();
            for(HighRepurchaseCategory category : highRepurchaseCategories){
                if(category.getStartDate().equals(start) &&
                        category.getEndDate().equals(end) &&
                category.getTopNumber() == number){
                    result.add(category);
                }
            }

            // 构建成功响应（与响应示例格式完全一致）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 通用服务端异常处理（打印日志+统一500错误响应）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/abnormal/repeat-orders")
    public ResponseEntity<Object> detectRepeatOrders(
            @RequestParam Integer timeWindow,
            @RequestParam String startDate,
            @RequestParam String endDate
    ) {
        // 1. 时间窗口参数校验（非空+正整数，确保时间窗口有效）
        if (timeWindow == null) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "时间窗口参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        if (timeWindow <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "时间窗口必须为正整数（单位：分钟）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 日期参数非空校验（复用/kpi、/daily接口的日期校验逻辑）
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 日期格式校验（仅支持yyyy-MM-dd，严格模式避免非法日期）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 日期逻辑校验（开始日期不能晚于结束日期）
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 5. 调用服务层获取数据并处理响应（遵循项目"try-catch捕获异常+统一响应格式"逻辑）
        try {
            List<Map<String, Object>> repeatOrderUserList =
                    electronicsSaleService.detectRepeatOrderByUser(timeWindow, start, end);

            // 6. 校验数据：无重复下单用户时返回空列表（非404，因"无异常"属于正常结果）
            // 说明：与"未查询到数据"的业务场景区分，此处"无重复下单用户"是有效结果，故不抛404
            if (repeatOrderUserList == null) {
                repeatOrderUserList = new ArrayList<>();
            }

            for(Map<String, Object> user : repeatOrderUserList){
                Object obj = user.get("user_id"); // 从Map/查询结果中获取值，实际类型是Double
                Long userId = 0L; // 初始化默认值（Long类型默认值用0L，避免自动装箱问题）

                if (obj instanceof Double) {
                    // 关键：调用Double的longValue()方法转为long，再自动装箱为Long
                    Double doubleValue = (Double) obj;
                    userId = doubleValue.longValue(); // 或 Long.valueOf(doubleValue.longValue())
                } else if (obj instanceof Long) {
                    // 兼容可能的Long类型（可选，避免后续逻辑异常）
                    userId = (Long) obj;
                } else if (obj instanceof Integer) {
                    // 兼容Integer类型（如数据库返回INT类型）
                    Integer intValue = (Integer) obj;
                    userId = intValue.longValue();
                } else if (obj == null) {
                    // 处理null情况（可选，按业务需求设默认值或抛异常）
                    userId = 0L; // 或 throw new IllegalArgumentException("order_id不能为空");
                }

                Object repeatOrderCountObj = user.get("repeat_order_count");
                Integer repeatOrderCount = 0; // 默认值
                if (repeatOrderCountObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long repeatOrderCountLong = (Long) repeatOrderCountObj;
                    repeatOrderCount = repeatOrderCountLong.intValue();
                } else if (repeatOrderCountObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    repeatOrderCount = (Integer) repeatOrderCountObj;
                }

                Date firstRepeatTime = (Date) user.get("first_repeat_time");
                Date lastRepeatTime = (Date) user.get("last_repeat_time");
                String relatedOrderIds = null;

                RepeatOrderByUser repeatOrderByUser = new RepeatOrderByUser(
                        null,
                        timeWindow,
                        start,
                        end,
                        userId,
                        repeatOrderCount,
                        firstRepeatTime,
                        lastRepeatTime,
                        relatedOrderIds,
                        null
                );
                repeatOrderByUserService.insert(repeatOrderByUser);
            }

            // 7. 构建成功响应（与示例格式完全一致）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", repeatOrderUserList);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 8. 通用服务端异常处理（打印日志+返回500，沿用项目所有接口的异常处理风格）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/abnormal/repeat-orders1")
    public ResponseEntity<Object> detectRepeatOrders1(
            @RequestParam Integer timeWindow,
            @RequestParam String startDate,
            @RequestParam String endDate
    ) {
        // 1. 时间窗口参数校验（非空+正整数，确保时间窗口有效）
        if (timeWindow == null) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "时间窗口参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        if (timeWindow <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "时间窗口必须为正整数（单位：分钟）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 日期参数非空校验（复用/kpi、/daily接口的日期校验逻辑）
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 日期格式校验（仅支持yyyy-MM-dd，严格模式避免非法日期）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 日期逻辑校验（开始日期不能晚于结束日期）
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 5. 调用服务层获取数据并处理响应（遵循项目"try-catch捕获异常+统一响应格式"逻辑）
        try {
            List<RepeatOrderByUser> repeatOrderUserList = repeatOrderByUserService.selectAll();
            List<RepeatOrderByUser> result = new ArrayList<>();
            for(RepeatOrderByUser repeatOrderByUser : repeatOrderUserList){
                if(repeatOrderByUser.getTimeWindow().equals(timeWindow) &&
                repeatOrderByUser.getStartDate().equals(start) &&
                repeatOrderByUser.getEndDate().equals(end)){
                    result.add(repeatOrderByUser);
                }
            }

            // 7. 构建成功响应（与示例格式完全一致）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 8. 通用服务端异常处理（打印日志+返回500，沿用项目所有接口的异常处理风格）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/abnormal/high-price-orders")
    public ResponseEntity<Object> detectHighPriceOrders(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        // 1. 日期参数非空校验（复用项目统一校验逻辑）
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 日期格式校验（严格校验 yyyy-MM-dd，避免非法日期如 2023-02-30）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 日期逻辑校验（开始日期不能晚于结束日期）
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取异常高价订单数据并处理响应
        try {
            // 服务层需实现异常高价判定逻辑（如：订单总金额与对应品类平均价格偏差率超过阈值则判定为异常）
            // 返回数据需包含：orderId、userId、orderTime、totalAmount、avgCategoryPrice、deviationRate、productCount
            List<Map<String, Object>> highPriceOrders =
                    electronicsSaleService.detectAbnormalHighPriceOrder(start, end);

            // 5. 处理无异常订单场景（无异常属于正常结果，返回空列表而非 404）
            if (highPriceOrders == null) {
                highPriceOrders = new ArrayList<>();
            }

            for(Map<String, Object> highPriceOrder : highPriceOrders){
                String num = highPriceOrder.get("order_id").toString();
                Long orderId;
                try {
                    // 1. Double解析科学计数法（自动转为浮点数）
                    Double doubleValue = Double.valueOf(num);
                    // 2. 转为long（注意：Double值必须在long范围内，否则会溢出）
                    orderId = doubleValue.longValue();
                    System.out.println(orderId); // 输出：1515915625465546752（因Double精度，末尾可能有微小变化）
                } catch (NumberFormatException e) {
                    // 处理格式错误（如非科学计数法字符串）
                    System.err.println("字符串格式错误：" + e.getMessage());
                    orderId = 0L; // 设默认值
                } catch (ArithmeticException e) {
                    // 处理数值溢出（如Double值超过long范围）
                    System.err.println("数值超出long范围：" + e.getMessage());
                    orderId = 0L;
                }

                num = highPriceOrder.get("product_id").toString();
                Long productId;
                try {
                    // 1. Double解析科学计数法（自动转为浮点数）
                    Double doubleValue = Double.valueOf(num);
                    // 2. 转为long（注意：Double值必须在long范围内，否则会溢出）
                    productId = doubleValue.longValue();
                    System.out.println(productId); // 输出：1515915625465546752（因Double精度，末尾可能有微小变化）
                } catch (NumberFormatException e) {
                    // 处理格式错误（如非科学计数法字符串）
                    System.err.println("字符串格式错误：" + e.getMessage());
                    productId = 0L; // 设默认值
                } catch (ArithmeticException e) {
                    // 处理数值溢出（如Double值超过long范围）
                    System.err.println("数值超出long范围：" + e.getMessage());
                    productId = 0L;
                }

                BigInteger priceBigInt = (BigInteger) highPriceOrder.get("price");
                BigDecimal price = new BigDecimal(priceBigInt);

                BigInteger abnormalThresholdInt = (BigInteger) highPriceOrder.get("abnormal_threshold");
                BigDecimal abnormalThreshold = new BigDecimal(abnormalThresholdInt);

                num = highPriceOrder.get("user_id").toString();
                Long userId;
                try {
                    // 1. Double解析科学计数法（自动转为浮点数）
                    Double doubleValue = Double.valueOf(num);
                    // 2. 转为long（注意：Double值必须在long范围内，否则会溢出）
                    userId = doubleValue.longValue();
                    System.out.println(userId); // 输出：1515915625465546752（因Double精度，末尾可能有微小变化）
                } catch (NumberFormatException e) {
                    // 处理格式错误（如非科学计数法字符串）
                    System.err.println("字符串格式错误：" + e.getMessage());
                    userId = 0L; // 设默认值
                } catch (ArithmeticException e) {
                    // 处理数值溢出（如Double值超过long范围）
                    System.err.println("数值超出long范围：" + e.getMessage());
                    userId = 0L;
                }

                Date eventTime = (Date) highPriceOrder.get("event_time");

                String abnormalType = (String) highPriceOrder.get("abnormal_type");

                AbnormalHighPriceOrder abnormalHighPriceOrder = new AbnormalHighPriceOrder(
                        null, start, end, orderId, productId,
                        price, abnormalThreshold, userId, eventTime,
                        abnormalType, null);
                abnormalHighPriceOrderService.insert(abnormalHighPriceOrder);
            }

            // 6. 构建成功响应（严格匹配示例格式）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", highPriceOrders);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 7. 服务端异常统一处理（沿用项目日志打印+500错误响应逻辑）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/abnormal/high-price-orders1")
    public ResponseEntity<Object> detectHighPriceOrders1(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        // 1. 日期参数非空校验（复用项目统一校验逻辑）
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 日期格式校验（严格校验 yyyy-MM-dd，避免非法日期如 2023-02-30）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 日期逻辑校验（开始日期不能晚于结束日期）
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取异常高价订单数据并处理响应
        try {
            List<AbnormalHighPriceOrder> result = new ArrayList<>();
            List<AbnormalHighPriceOrder> abnormalHighPriceOrders =
                    abnormalHighPriceOrderService.selectAll();
            for(AbnormalHighPriceOrder abnormalHighPriceOrder : abnormalHighPriceOrders){
                if(abnormalHighPriceOrder.getStartDate().equals(start) &&
                abnormalHighPriceOrder.getEndDate().equals(end)){
                    result.add(abnormalHighPriceOrder);
                }
            }

            // 6. 构建成功响应（严格匹配示例格式）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 7. 服务端异常统一处理（沿用项目日志打印+500错误响应逻辑）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/abnormal/consume-users")
    public ResponseEntity<Object> detectAbnormalConsumeUsers(
            @RequestParam Integer orderCountThreshold,
            @RequestParam Double amountThreshold,
            @RequestParam String startDate,
            @RequestParam String endDate) {

        // 1. 阈值参数校验（非空+数值合法性，匹配错误响应示例）
        // 订单数量阈值：非空+正整数
        if (orderCountThreshold == null) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "订单数量阈值不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        // 金额阈值：非空+正数（支持小数，如100.50）
        if (amountThreshold == null) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "消费金额阈值不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        // 阈值数值合法性：必须大于0（匹配“订单数量阈值和金额阈值必须大于0”错误响应）
        if (orderCountThreshold <= 0 || amountThreshold <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "订单数量阈值和金额阈值必须大于0");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 日期参数校验（复用原有接口的日期校验逻辑，保证一致性）
        // 2.1 日期非空校验
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        // 2.2 日期格式校验（严格匹配 yyyy-MM-dd，避免非法日期如2023-02-30）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        // 2.3 日期逻辑校验：开始日期不能晚于结束日期
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 调用服务层获取异常消费用户数据（遵循原有接口的服务调用逻辑）
        try {
            // 服务层需实现：根据“订单数>阈值”且“消费金额>阈值”筛选用户，返回指定字段列表
            // 返回数据要求：按订单数降序排列，包含userId、userName、orderCount、totalAmount、avgOrderAmount、firstOrderTime、lastOrderTime
            List<Map<String, Object>> abnormalUserList =
                    electronicsSaleService.detectAbnormalConsumeUser(orderCountThreshold, amountThreshold, start, end);

            // 4. 处理无异常用户场景（无异常属于正常结果，返回空列表而非404）
            if (abnormalUserList == null) {
                abnormalUserList = new ArrayList<>();
            }

            for(Map<String, Object> user : abnormalUserList){
                String num = user.get("user_id").toString();
                Long userId;
                try {
                    // 1. Double解析科学计数法（自动转为浮点数）
                    Double doubleValue = Double.valueOf(num);
                    // 2. 转为long（注意：Double值必须在long范围内，否则会溢出）
                    userId = doubleValue.longValue();
                    System.out.println(userId); // 输出：1515915625465546752（因Double精度，末尾可能有微小变化）
                } catch (NumberFormatException e) {
                    // 处理格式错误（如非科学计数法字符串）
                    System.err.println("字符串格式错误：" + e.getMessage());
                    userId = 0L; // 设默认值
                } catch (ArithmeticException e) {
                    // 处理数值溢出（如Double值超过long范围）
                    System.err.println("数值超出long范围：" + e.getMessage());
                    userId = 0L;
                }

                Object orderCountObj = user.get("order_count");
                Integer orderCount = 0; // 默认值
                if (orderCountObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long repeatOrderCountLong = (Long) orderCountObj;
                    orderCount = repeatOrderCountLong.intValue();
                } else if (orderCountObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    orderCount = (Integer) orderCountObj;
                }

                BigInteger totalConsumeAmountInt = (BigInteger) user.get("total_consume_amount");
                BigDecimal totalConsumeAmount = new BigDecimal(totalConsumeAmountInt);

                String abnormalMark = (String) user.get("abnormal_mark");

                double numamount = amountThreshold; // 科学计数法double
                String numStr = String.valueOf(numamount);
                BigDecimal correctBigDecimal = new BigDecimal(numStr);
                System.out.println(correctBigDecimal);

                AbnormalConsumeUser abnormalConsumeUser = new AbnormalConsumeUser(
                        null,
                        orderCountThreshold,
                        correctBigDecimal,
                        start,
                        end,
                        userId,
                        orderCount,
                        totalConsumeAmount,
                        abnormalMark,
                        null
                );
                abnormalConsumeUserService.insert(abnormalConsumeUser);
            }

            // 5. 构建成功响应（严格匹配响应示例格式）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", abnormalUserList);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 6. 服务端异常统一处理（沿用原有接口的日志打印+500错误响应逻辑）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/abnormal/consume-users1")
    public ResponseEntity<Object> detectAbnormalConsumeUsers1(
            @RequestParam Integer orderCountThreshold,
            @RequestParam Double amountThreshold,
            @RequestParam String startDate,
            @RequestParam String endDate) {

        // 1. 阈值参数校验（非空+数值合法性，匹配错误响应示例）
        // 订单数量阈值：非空+正整数
        if (orderCountThreshold == null) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "订单数量阈值不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        // 金额阈值：非空+正数（支持小数，如100.50）
        if (amountThreshold == null) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "消费金额阈值不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        // 阈值数值合法性：必须大于0（匹配“订单数量阈值和金额阈值必须大于0”错误响应）
        if (orderCountThreshold <= 0 || amountThreshold <= 0) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "订单数量阈值和金额阈值必须大于0");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 日期参数校验（复用原有接口的日期校验逻辑，保证一致性）
        // 2.1 日期非空校验
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期和结束日期不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        // 2.2 日期格式校验（严格匹配 yyyy-MM-dd，避免非法日期如2023-02-30）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        } catch (ParseException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "日期格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
        // 2.3 日期逻辑校验：开始日期不能晚于结束日期
        if (start.after(end)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "开始日期不能晚于结束日期");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 调用服务层获取异常消费用户数据（遵循原有接口的服务调用逻辑）
        try {
            double numamount = amountThreshold;
            String numStr = String.valueOf(numamount);
            BigDecimal correctBigDecimal = new BigDecimal(numStr);
            System.out.println(correctBigDecimal);
            List<AbnormalConsumeUser> result = new ArrayList<>();
            List<AbnormalConsumeUser> abnormalUserList = abnormalConsumeUserService.selectAll();
            for (AbnormalConsumeUser abnormalUser : abnormalUserList) {
                if(abnormalUser.getOrderCountThreshold().equals(orderCountThreshold)
                && abnormalUser.getAmountThreshold().compareTo(correctBigDecimal) == 0
                && abnormalUser.getStartDate().equals(start)
                && abnormalUser.getEndDate().equals(end)){
                    result.add(abnormalUser);
                }
            }

            // 5. 构建成功响应（严格匹配响应示例格式）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 6. 服务端异常统一处理（沿用原有接口的日志打印+500错误响应逻辑）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/age-layer/category")
    public ResponseEntity<Object> getSalesByAgeLayerAndCategory(
            @RequestParam String ageLayer
    ) {
        // 1. 参数非空校验
        if (ageLayer == null || ageLayer.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "年龄段参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 年龄段格式校验（必须符合"最小年龄-最大年龄"格式，如20-29）
        // 正则表达式：匹配"数字-数字"格式，且最小年龄≤最大年龄，年龄为正整数
        String ageLayerRegex = "^\\d+-\\d+$";
        if (!ageLayer.matches(ageLayerRegex)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "年龄段格式不正确，请使用\"最小年龄-最大年龄\"格式（如20-29）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取数据并处理响应
        try {
            // 调用服务层：传入拆分后的最小/最大年龄，获取按销量倒序的品类数据
            List<Map<String, Object>> ageLayerCategorySales =
                    electronicsSaleService.getCategoryByAgeLayer(ageLayer);

            // 校验数据：未查询到该年龄段的品类销量数据时返回404
            if (ageLayerCategorySales == null || ageLayerCategorySales.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 404);
                errorResponse.put("message", "未查询到" + ageLayer + "年龄段的品类销量数据");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }

            for(Map<String, Object> item : ageLayerCategorySales){
                String categoryCode = (String) item.get("category_code");

                Object volumeObj = item.get("volume");
                Integer volume = 0; // 默认值
                if (volumeObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long volumeLong = (Long) volumeObj;
                    volume = volumeLong.intValue();
                } else if (volumeObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    volume = (Integer) volumeObj;
                }

                String volumeRatio = (String) item.get("volumeratio");
                CategoryByAgeLayer categoryByAgeLayer = new CategoryByAgeLayer(null, ageLayer,
                        categoryCode, volume, volumeRatio, null);
                categoryByAgeLayerService.insert(categoryByAgeLayer);
            }

            // 构建成功响应（与响应示例格式完全一致）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", ageLayerCategorySales);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/age-layer/category1")
    public ResponseEntity<Object> getSalesByAgeLayerAndCategory1(
            @RequestParam String ageLayer
    ) {
        // 1. 参数非空校验
        if (ageLayer == null || ageLayer.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "年龄段参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 年龄段格式校验（必须符合"最小年龄-最大年龄"格式，如20-29）
        // 正则表达式：匹配"数字-数字"格式，且最小年龄≤最大年龄，年龄为正整数
        String ageLayerRegex = "^\\d+-\\d+$";
        if (!ageLayer.matches(ageLayerRegex)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "年龄段格式不正确，请使用\"最小年龄-最大年龄\"格式（如20-29）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取数据并处理响应
        try {
            List<CategoryByAgeLayer> result = new ArrayList<>();
            List<CategoryByAgeLayer> ageLayerCategorySales = categoryByAgeLayerService.selectAll();
            for(CategoryByAgeLayer item : ageLayerCategorySales){
                if(item.getAgeLayer().equals(ageLayer)){
                    result.add(item);
                }
            }

            // 构建成功响应（与响应示例格式完全一致）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/age-layer/user-power")
    public ResponseEntity<Object> getUserConsumptionPowerByAgeLayer(
            @RequestParam String ageLayer
    ) {
        // 1. 参数非空校验（沿用项目"参数为空返回400"的逻辑）
        if (ageLayer == null || ageLayer.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "年龄段参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 年龄段格式校验（必须符合"最小年龄-最大年龄"格式，如20-29）
        // 正则表达式：严格匹配"数字-数字"，避免非数字字符（如20-a、20_29）
        String ageLayerRegex = "^\\d+-\\d+$";
        if (!ageLayer.matches(ageLayerRegex)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "年龄段格式不正确，请使用\"最小年龄-最大年龄\"格式（如20-29）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 年龄段逻辑校验（拆分最小/最大年龄，确保1≤最小年龄≤最大年龄≤120，避免无效值）
        String[] ageParts = ageLayer.split("-");
        int minAge;
        int maxAge;
        try {
            // 转换年龄为整数（捕获非数字异常，如20.5-29）
            minAge = Integer.parseInt(ageParts[0]);
            maxAge = Integer.parseInt(ageParts[1]);
        } catch (NumberFormatException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "年龄段中的年龄必须为正整数（如20-29，不可为20.5-29或20-a）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 校验年龄范围合理性（避免150-200、29-20等无效逻辑）
        if (minAge < 1 || maxAge < 1 || minAge > maxAge || maxAge > 120) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "年龄段逻辑错误，需满足1≤最小年龄≤最大年龄≤120（如20-29）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 4. 调用服务层获取数据并处理响应（遵循项目"try-catch捕获异常+统一响应"逻辑）
        try {
            // 调用服务层：传入年龄段字符串（或拆分后的minAge/maxAge），获取TOP100消费能力数据
            // 服务层需保证返回结果按maxPrice降序排列，且最多100条
            List<Map<String, Object>> userPowerList =
                    electronicsSaleService.getUserPowerByAgeLayer(ageLayer);

            // 校验数据：未查询到该年龄段用户数据时返回404（参考/age-layer/category接口逻辑）
            if (userPowerList == null || userPowerList.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 404);
                errorResponse.put("message", "未查询到" + ageLayer + "年龄段的用户消费能力数据");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }

            // 构建成功响应（与示例格式完全一致：code=200、message=success、data含userId/maxPrice）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", userPowerList);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 通用服务端异常处理（打印日志+返回500，沿用项目统一逻辑）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/sex/category")
    public ResponseEntity<Object> getCategorySalesBySex(
            @RequestParam String sex
    ) {
        // 1. 参数非空校验（沿用项目"参数为空返回400"的统一逻辑）
        if (sex == null || sex.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "性别参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 性别合法性校验（仅支持"男"/"女"，与业务需求一致）
        if (!"男".equals(sex) && !"女".equals(sex)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "性别参数不合法，仅支持\"男\"或\"女\"");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 调用服务层获取数据并处理响应（遵循项目"try-catch捕获异常+统一响应格式"逻辑）
        try {
            // 调用服务层：传入指定性别，获取该性别下各品类的销量、占比（服务层需保证按销量倒序）
            // 服务层返回的List<Map>需包含"categoryCode"（品类编码）、"volume"（销量）、"volumeRatio"（占比，格式如"38.20%"）
            List<Map<String, Object>> sexCategorySales =
                    electronicsSaleService.getCategoryBySex(sex);

            // 4. 校验数据：未查询到该性别下的品类销量数据时返回404（参考/age-layer/category接口逻辑）
            if (sexCategorySales == null || sexCategorySales.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 404);
                errorResponse.put("message", "未查询到" + sex + "性别的品类销量数据");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }

            for (Map<String, Object> map : sexCategorySales) {
                String categoryCode = (String) map.get("category_code");

                Object volumeObj = map.get("volume");
                Integer volume = 0; // 默认值
                if (volumeObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long volumeLong = (Long) volumeObj;
                    volume = volumeLong.intValue();
                } else if (volumeObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    volume = (Integer) volumeObj;
                }

                String volumeRatio = (String) map.get("volumeratio");

                CategoryBySex categoryBySex = new CategoryBySex(null, sex, categoryCode,
                        volume, volumeRatio, null);
                categoryBySexService.insert(categoryBySex);
            }

            // 5. 构建成功响应（与示例格式完全一致：code=200、message=success、data含指定字段）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", sexCategorySales);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 通用服务端异常处理（打印日志+返回500，沿用项目统一逻辑）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/sex/category1")
    public ResponseEntity<Object> getCategorySalesBySex1(
            @RequestParam String sex
    ) {
        // 1. 参数非空校验（沿用项目"参数为空返回400"的统一逻辑）
        if (sex == null || sex.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "性别参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 性别合法性校验（仅支持"男"/"女"，与业务需求一致）
        if (!"男".equals(sex) && !"女".equals(sex)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "性别参数不合法，仅支持\"男\"或\"女\"");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 调用服务层获取数据并处理响应（遵循项目"try-catch捕获异常+统一响应格式"逻辑）
        try {
            List<CategoryBySex> result = new ArrayList<>();
            List<CategoryBySex> sexCategorySales =
                    categoryBySexService.selectAll();
            for(CategoryBySex categoryBySex : sexCategorySales){
                if(categoryBySex.getSex().equals(sex)){
                    result.add(categoryBySex);
                }
            }

            // 5. 构建成功响应（与示例格式完全一致：code=200、message=success、data含指定字段）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 通用服务端异常处理（打印日志+返回500，沿用项目统一逻辑）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/sex/user-power")
    public ResponseEntity<Object> getUserConsumptionPowerBySex(
            @RequestParam String sex
    ) {
        // 1. 参数非空校验（沿用项目"参数为空返回400"的统一逻辑，与/sex/category接口保持一致）
        if (sex == null || sex.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "性别参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 性别合法性校验（仅支持"男"/"女"，与业务需求一致，复用/sex/category的校验逻辑）
        if (!"男".equals(sex) && !"女".equals(sex)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "性别参数不合法，仅支持\"男\"或\"女\"");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 调用服务层获取数据并处理响应（遵循项目"try-catch捕获异常+统一响应格式"逻辑）
        try {
            List<Map<String, Object>> sexUserPowerList =
                    electronicsSaleService.getUserPowerBySex(sex);

            // 4. 校验数据：未查询到该性别下的用户消费能力数据时返回404（参考/age-layer/user-power接口逻辑）
            if (sexUserPowerList == null || sexUserPowerList.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 404);
                errorResponse.put("message", "未查询到" + sex + "性别的用户消费能力数据");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }

            // 5. 构建成功响应（与示例格式完全一致：code=200、message=success、data含userId/maxPrice）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", sexUserPowerList);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 通用服务端异常处理（打印日志+返回500，沿用项目统一逻辑）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/province/category")
    public ResponseEntity<Object> getCategorySalesByProvince(
            @RequestParam String province
    ) {
        // 1. 参数非空校验（沿用项目"参数为空返回400"的统一逻辑，参考/sex/category接口）
        if (province == null || province.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "省份参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 省份参数合法性校验（基础格式校验，避免空字符串/特殊字符，参考项目参数校验风格）
        // 规则：仅允许中文、省份标准名称（如"广东""北京"，排除特殊字符/数字）
        String provinceRegex = "^[\\u4e00-\\u9fa5]{2,10}$"; // 2-10位中文（覆盖所有省份/直辖市/自治区名称长度）
        if (!province.matches(provinceRegex)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "省份参数不合法，请输入标准省份名称（如：广东、北京）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            List<Map<String, Object>> provinceCategorySales =
                    electronicsSaleService.getCategoryByProvince(province);

            // 4. 校验数据：未查询到该省份下的品类销量数据时返回404（参考/age-layer/category、/sex/category接口逻辑）
            if (provinceCategorySales == null || provinceCategorySales.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 404);
                errorResponse.put("message", "未查询到" + province + "的品类销量数据");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }

            for(Map<String, Object> categorySale : provinceCategorySales){
                String categoryCode = (String) categorySale.get("category_code");

                Object volumeObj = categorySale.get("volume");
                Integer volume = 0; // 默认值
                if (volumeObj instanceof Long) {
                    // 先转为Long，再通过intValue()转为Integer
                    Long volumeLong = (Long) volumeObj;
                    volume = volumeLong.intValue();
                } else if (volumeObj instanceof Integer) {
                    // 兼容可能的Integer类型
                    volume = (Integer) volumeObj;
                }

                String volumeRatio = (String) categorySale.get("volumeratio");

                CategoryByProvince categoryByProvince = new CategoryByProvince(null , province,
                        categoryCode, volume, volumeRatio, null);
                categoryByProvinceService.insert(categoryByProvince);
            }

            // 5. 构建成功响应（与示例格式完全一致：code=200、message=success、data含3个指定字段）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", provinceCategorySales);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 通用服务端异常处理（打印日志+返回500，沿用项目统一逻辑，参考所有接口的异常处理）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/province/category1")
    public ResponseEntity<Object> getCategorySalesByProvince1(
            @RequestParam String province
    ) {
        // 1. 参数非空校验（沿用项目"参数为空返回400"的统一逻辑，参考/sex/category接口）
        if (province == null || province.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "省份参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 省份参数合法性校验（基础格式校验，避免空字符串/特殊字符，参考项目参数校验风格）
        // 规则：仅允许中文、省份标准名称（如"广东""北京"，排除特殊字符/数字）
        String provinceRegex = "^[\\u4e00-\\u9fa5]{2,10}$"; // 2-10位中文（覆盖所有省份/直辖市/自治区名称长度）
        if (!province.matches(provinceRegex)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "省份参数不合法，请输入标准省份名称（如：广东、北京）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            List<CategoryByProvince> provinceCategorySales =
                    categoryByProvinceService.selectAll();
            List<CategoryByProvince> result = new ArrayList<>();
            for(CategoryByProvince categoryByProvince : provinceCategorySales){
                if(categoryByProvince.getProvince().equals(province)){
                    result.add(categoryByProvince);
                }
            }

            // 5. 构建成功响应（与示例格式完全一致：code=200、message=success、data含3个指定字段）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", result);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 通用服务端异常处理（打印日志+返回500，沿用项目统一逻辑，参考所有接口的异常处理）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/province/user-power")
    public ResponseEntity<Object> getUserPowerByProvince(
            @RequestParam String province
    ) {
        // 1. 参数非空校验（沿用项目"参数为空返回400"的统一逻辑，参考/sex/user-power、/province/category接口）
        if (province == null || province.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "省份参数不能为空");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 2. 省份参数合法性校验（复用/province/category的校验规则，确保省份格式统一）
        // 规则：仅允许中文、标准省份名称（如"广东""北京"，排除特殊字符/数字/过短/过长名称）
        String provinceRegex = "^[\\u4e00-\\u9fa5]{2,10}$"; // 2-10位中文（覆盖所有省份/直辖市/自治区名称长度）
        if (!province.matches(provinceRegex)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "省份参数不合法，请输入标准省份名称（如：广东、北京）");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 3. 调用服务层获取数据并处理响应（遵循项目"try-catch捕获异常+统一响应格式"逻辑）
        try {
            List<Map<String, Object>> provinceUserPowerList =
                    electronicsSaleService.getUserPowerByProvince(province);

            // 4. 校验数据：未查询到该省份下的用户消费能力数据时返回404（参考/age-layer/user-power、/sex/user-power接口逻辑）
            if (provinceUserPowerList == null || provinceUserPowerList.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 404);
                errorResponse.put("message", "未查询到" + province + "的用户消费能力数据");
                errorResponse.put("data", null);
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }

            // 5. 构建成功响应（与示例格式完全一致：code=200、message=success、data含2个指定字段）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "success");
            successResponse.put("data", provinceUserPowerList);

            return new ResponseEntity<>(successResponse, HttpStatus.OK);
        } catch (Exception e) {
            // 通用服务端异常处理（打印日志+返回500，沿用项目所有接口的异常处理风格）
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务端异常，请稍后再试");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/test")
    public ResponseEntity<Object> test() {
        Map<String, Object> successResponse = new HashMap<>();
        successResponse.put("code", 200);
        successResponse.put("message", "success");
        successResponse.put("data", "tes");
        return new ResponseEntity<>(successResponse, HttpStatus.OK);
    }
}
